//
//  ZhuanSearchViewController.m
//  specialine
//
//  Created by 往返网络 on 17/7/17.
//  Copyright © 2017年 com. All rights reserved.
//

#import "ZhuanSearchViewController.h" //转账搜索联系人vc
#import "PublicMethod.h"
#define return_tag 2000
//定义转账URL
#define URL_SEARCH [NSString stringWithFormat:@"%@/Appcustomernewer/Pay/payTransferUser?type=get",BASE_URL]
@interface ZhuanSearchViewController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property (nonatomic,strong)AFHTTPSessionManager* manger;
@property (nonatomic,strong)NSMutableArray * resultArray;
@end
@implementation ZhuanSearchViewController
{
    
    UISearchBar * searchbar; // 搜索条
    UITableView * tableview;
    NSString * mobile ;//手机号

}
- (void)viewWillAppear:(BOOL)animated{
//    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    
}
- (void)viewWillDisappear:(BOOL)animated{
//    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    // Do any additional setup after loading the view.
}
- (void)createUI{
    
    float fontsize = 17;
    
    fontsize = SCREEN_H < 667 ? 15 : 19;
    
    if (SCREEN_H == 667) {
        fontsize = 17;
    }

    [self.navigationItem setHidesBackButton:TRUE animated:NO]; //去掉返回按钮
    tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 30.0/H_BASE*SCREEN_H, SCREEN_W, SCREEN_H-30.0/H_BASE*SCREEN_H) style:UITableViewStylePlain];
    tableview.backgroundColor = COLORRGBA(239, 239, 239, 1);
    tableview.rowHeight = 44;
    tableview.delegate = self;
    tableview.dataSource = self;
    [self.view addSubview:tableview];
    tableview.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
//    tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
//    [tableview registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 620.0/W_BASE*SCREEN_W, 60.0/H_BASE*SCREEN_H)];//allocate titleView
    UIColor *color =  self.navigationController.navigationBar.barTintColor;
    [titleView setBackgroundColor:color];
    UISearchBar *searchBar = [[UISearchBar alloc] init];
    searchBar.delegate = self;
    searchBar.frame = CGRectMake(0, 0, 620.0/W_BASE*SCREEN_W, 60.0/H_BASE*SCREEN_H);
    searchBar.layer.cornerRadius = fontsize-4;
    searchBar.layer.masksToBounds = YES;
    [searchBar.layer setBorderWidth:fontsize-15];
    [searchBar.layer setBorderColor:[UIColor whiteColor].CGColor];  //设置边框为白色
    searchBar.keyboardType = UIKeyboardTypeDefault;
    searchbar.showsCancelButton = YES;
    searchbar.returnKeyType = UIReturnKeySearch;
    searchBar.placeholder = @"搜索手机号";
    [titleView addSubview:searchBar];
    searchBar.backgroundColor = COLORRGBA(239, 239, 239, 1);

    //Set to titleView
    [self.navigationItem.titleView sizeToFit];
    self.navigationItem.titleView = titleView;
    
    UIButton * cancelbtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_W-100.0/W_BASE*SCREEN_W, 0, 75.0/W_BASE*SCREEN_W, 60.0/H_BASE*SCREEN_H)];
    [cancelbtn setTitle:@"取消" forState:UIControlStateNormal];
    cancelbtn.titleLabel.font = [UIFont systemFontOfSize:fontsize-2];
    cancelbtn.titleLabel.textAlignment = NSTextAlignmentRight;
    [cancelbtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    UIBarButtonItem * rigtitem = [[UIBarButtonItem alloc]initWithCustomView:cancelbtn];
    self.navigationItem.rightBarButtonItem = rigtitem;
    [cancelbtn addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
    //
    
    
}
#pragma mark --- searchbar- Delegate

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
//    [searchBar setShowsCancelButton:YES animated:YES]; //显示取消按钮

    return YES;
    
}
#pragma mark  --------- -- - - - - - - 查询当前银行卡－ － －－ － － － － － －
- (void)searchMobile{
    
    //请求账号信息，余额等，赋值。。
    UIImageView * ima = [PublicMethod startAnimation];
    NSString * token = [[NSUserDefaults standardUserDefaults]objectForKey:USER_TOCKE];
    NSString *  mobilestr = [mobile stringByReplacingOccurrencesOfString: @" " withString: @""];
    NSLog(@"searchbar text  %@",searchbar.text);
    NSString * url = [NSString stringWithFormat:@"%@&token=%@&mobile=%@",URL_SEARCH,token,mobilestr];
    
    NSLog(@"搜索手机号 url %@",url);
    [self.manger GET:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if (responseObject) {
            NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSInteger code = [dict[@"code"]integerValue];
            if (code == 0) {
                // 停止动画
                [ima stopAnimating];
                //获得银行卡号，余额，银行名称，logo ID值
                NSArray * infoarr  = (NSArray*)dict[@"info"];
                NSLog(@"infoarr count %ld",infoarr.count);
                self.resultArray = [NSMutableArray arrayWithArray:infoarr];
                NSLog(@"result count %ld",self.resultArray.count);
                for (NSDictionary *dic  in self.resultArray) {
                    
                    NSLog(@" each dic %@",dic);
                }
                [tableview reloadData];
            
            }else{
                
                [ima stopAnimating];
                ALERT(@"提示", dict[@"info"], self, @"确定", nil);
                
            }
            
        }
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        
        ALERT(@"提示", @"网络请求失败", self, @"确定", nil);
        [ima stopAnimating];
        
    }];
}


- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    NSLog(@"searchtext %@",searchText);
    mobile = searchText;
    //搜索框中输入关键字进行搜索
    //清楚数据源
//    NSLog(@"%@", self.dataSource);
//    [self.resultArray removeAllObjects];
    //加个多线程，否则数量量大的时候，有明显的卡顿现象
    //这里最好放在数据库里面再进行搜索，效率会更快一些
//    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
//    dispatch_async(globalQueue, ^{
//        
//        if (searchText!=nil && searchText.length>0) {
//            
            //遍历需要搜索的所有内容，其中self.dataArray为存放总数据的数组
            
//            if ([self.historyTypeNumber isEqualToString:@"1"] ||[self.historyTypeNumber isEqualToString:@"2"] ) {
//                
//                
//                for (NSDictionary * dict in self.dataSource) {
//                    
//                    
//                    
//                    NSString *tempStr = dict[@"fromname"];
//                    
//                    
//                    //----------->把所有的搜索结果转成成拼音
//                    NSString *pinyin = [self transformToPinyin:tempStr];
//                    
//                    NSLog(@"pinyin--%@",pinyin);
//                    
//                    if ([pinyin rangeOfString:searchText options:NSCaseInsensitiveSearch].length >0 ) {
//                        
//                        [self.resultArray addObject:dict];
//                    }
//                    
//                }
//            }
//            else{
//                
//                for (int i = 0; i< self.dataSource.count; i++) {
//                    
//                    NSString *tempStr = self.dataSource[i];
//                    
//                    NSString *pinyin = [self transformToPinyin:tempStr];
//                    
//                    
//                    if ([pinyin rangeOfString:searchText options:NSCaseInsensitiveSearch].length >0 ) {
//                        
//                        [self.resultArray addObject:tempStr];
//                    }
//                    
//                }
//                
//            }
//            
//        }else{
//            
//            self.resultArray = [NSMutableArray arrayWithArray:self.dataSource];
//            
//        }
//        //回到主线程
//        dispatch_async(dispatch_get_main_queue(), ^{
//            
//            [tableview reloadData];
//            
//        });
        
//    });
    
    
    
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    
    NSLog(@"cancel");
    [self.navigationController popViewControllerAnimated:YES];
    
}


#pragma mark -- Tableview-Delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.resultArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 80.0/H_BASE*SCREEN_H;

}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    float fontsize = 17;
    
    fontsize = SCREEN_H < 667 ? 15 : 19;
    
    if (SCREEN_H == 667) {
        fontsize = 17;
    }
    
    
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    UILabel * namelab;
    UILabel * phonelab;
    
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        namelab = [[UILabel alloc]initWithFrame:CGRectMake(25.0/W_BASE*SCREEN_W, 0, 154.0/W_BASE*SCREEN_W, 80.0/H_BASE*SCREEN_H)];
        namelab.font = [UIFont systemFontOfSize:fontsize-3];
        namelab.textColor = [UIColor blackColor];
        namelab.textAlignment = NSTextAlignmentLeft;
        [cell.contentView addSubview:namelab];
        
        phonelab = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_W-25.0/W_BASE*SCREEN_W-200.0/W_BASE*SCREEN_W, 0, 200.0/W_BASE*SCREEN_W, 80.0/H_BASE*SCREEN_H)];
        phonelab.textAlignment = NSTextAlignmentRight;
        phonelab.font = [UIFont systemFontOfSize:fontsize-3];
        phonelab.textColor = [UIColor blackColor];
        [cell.contentView addSubview:phonelab];
       

    }
//    cell.backgroundColor = COLORRGBA(255, 255, 266, 1);

    NSDictionary * dict = self.resultArray[indexPath.row];
    if ([dict[@"user_type"]isEqualToString:@"1"]) {
        namelab.text = [NSString stringWithFormat:@"%@(货主)",dict[@"user_name"]];
    }else if ([dict[@"user_type"]isEqualToString:@"2"]){
        namelab.text = [NSString stringWithFormat:@"%@(专线)",dict[@"user_name"]];
    }
    phonelab.text  = mobile;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary * dict = self.resultArray[indexPath.row];
    NSString * user_type = dict[@"user_type"];
    self.backBlock (dict[@"user_name"],mobile,user_type,dict);
    [self.navigationController popViewControllerAnimated:YES];
    
}



- (NSString *)transformToPinyin:(NSString *)aString
{
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:aString];
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    NSArray *pinyinArray = [str componentsSeparatedByString:@" "];
    NSMutableString *allString = [NSMutableString new];
    
    int count = 0;
    
    for (int  i = 0; i < pinyinArray.count; i++)
    {
        
        for(int i = 0; i < pinyinArray.count;i++)
        {
            if (i == count) {
                [allString appendString:@"#"];//区分第几个字母
            }
            [allString appendFormat:@"%@",pinyinArray[i]];
            
        }
        [allString appendString:@","];
        count ++;
        
    }
    
    NSMutableString *initialStr = [NSMutableString new];//拼音首字母
    
    for (NSString *s in pinyinArray)
    {
        if (s.length > 0)
        {
            
            [initialStr appendString:  [s substringToIndex:1]];
        }
    }
    
    [allString appendFormat:@"#%@",initialStr];
    [allString appendFormat:@",#%@",aString];
    
    return allString;
}

#pragma mark - - - - - - - - - - -  Action - - - - - - - - - - - - -
- (void)enterClick:(UIButton *)btn{
    
    switch (btn.tag) {
        case return_tag:
            //返回
            [self.navigationController popViewControllerAnimated:YES];
            break;
            
               default:
            break;
            
    }
}
- (void)cancel{

    [self.navigationController popViewControllerAnimated:YES];

}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{

    return YES;

}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"search");
    [self searchMobile];

}

#pragma mark - - -- - - - 懒加载 ---- - -- - -

- (NSMutableArray *)resultArray{

    if (!_resultArray) {
        _resultArray = [NSMutableArray array];
    }
    return _resultArray;

}
- (AFHTTPSessionManager*)manger{
    
    if (!_manger) {
        
        _manger = [AFHTTPSessionManager manager];
        
        _manger.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        _manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", nil];
    }
    return _manger;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
